<template>
  <div class="leaveRecord-warp">
    <a-row>
      <a-col :span="24">
        <a-range-picker
          style="width: 100%"
          :show-time="{ format: 'HH:mm' }"
          format="YYYY-MM-DD HH:mm"
          size="large"
          :placeholder="['选择开始时间', '选择结束时间']"
          @change="timeChange"
          allowClear
        />
      </a-col>
    </a-row>
    <div></div>
    <div class="content">
      <div class="add">
        <a-button type="primary" @click="handleAdd">
          <template #icon><PlusOutlined /></template>
          请假申请
        </a-button>
      </div>
      <a-table
        row-key="code"
        :scroll="{ y: `calc(100vh - 196px)` }"
        :dataSource="state.dataSource"
        :columns="columns"
        :pagination="false"
      >
        <template #expandedRowRender="{ record }">
          <p style="margin: 0">请假开始时间： {{ record.startTime }}</p>
          <p style="margin: 0">请假结束时间： {{ record.endTime }}</p>
          <p style="margin: 0">情况说明： {{ record.reason }}</p>
          <p style="margin: 0" v-if="record.status === 3">
            驳回原因： {{ record.rejectReason }}
          </p>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag
              :color="
                record.status === 1
                  ? 'orange'
                  : record.status === 2
                  ? 'green'
                  : 'red'
              "
            >
              {{
                record.status === 1
                  ? "待审核"
                  : record.status === 2
                  ? "通过"
                  : "驳回"
              }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-button
              size="small"
              :disabled="
                moment().format('YYYY-MM-DD HH:mm:ss') > record.endTime ||
                record.status !== 1
              "
              @click="handleCancel(record)"
              >销假</a-button
            >
          </template>
        </template>
      </a-table>
    </div>
    <Pagination
      :total="state.total"
      @pageChange="pageChange"
      :pageConfig="state.page"
    ></Pagination>
  </div>
</template>

<script lang="ts" setup>
import { createVNode, onBeforeMount, onMounted } from "vue";
import { reactive } from "vue";
import Pagination from "@/components/pagination/index.vue";
import { ExclamationCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import { authRedict } from "@/utils/cas";
import { useAuthParse } from "@/api/auth/auth";
import { Modal, message } from "ant-design-vue";
import moment from "moment";
import { useStudentLeaveCancel, useStudentLeavePage } from "@/api";
const router = useRouter();
const state = reactive({
  total: 0,
  page: {
    pageNum: 1,
    pageSize: 20,
  },
  params: {
    startOn: "",
    endOn: "",
    employeeCode: "",
  },
  employeeName: "",
  dataSource: [],
});

const columns = [
  {
    title: "请假状态",
    dataIndex: "status",
    key: "status",
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    align: "center",
    dataIndex: "action",
    width: 90,
  },
];

const getData = async () => {
  let {
    result: { totalCount, items },
  } = await useStudentLeavePage({ ...state.params, ...state.page });
  state.dataSource = items || [];
  state.total = totalCount;
};

const handleAdd = () => {
  router.push({
    name: "AddLeave",
    query: {
      code: state.params.employeeCode,
      name: state.employeeName,
    },
  });
};

const pageChange = ({ pageNum, pageSize }) => {
  state.page.pageNum = pageNum;
  state.page.pageSize = pageSize;
  getData();
};

const handleCancel = (row) => {
  Modal.confirm({
    title: "是否确认销假？",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确认",
    onOk() {
      useStudentLeaveCancel({ code: row.code }).then((res) => {
        if (res.success) {
          message.success("操作成功", 2);
          getData();
        } else {
          message.error("操作失败，请稍后再试！", 2);
        }
      });
    },
    onCancel() {
      console.log("返回");
    },
  });
};

const timeChange = (_: any, dateString: string[]) => {
  state.params.startOn = dateString[0] !== "" ? dateString[0] + ":00" : "";
  state.params.endOn = dateString[1] !== "" ? dateString[1] + ":00" : "";
  getData();
};

onBeforeMount(() => {
  if (!sessionStorage.getItem("code")) {
    authRedict("http://mjkq.cqzhxy.cn:18088/m/student/leaveRecord");
  }
});

const initState = () => {
  if (!sessionStorage.getItem("code")) {
    useAuthParse("http://mjkq.cqzhxy.cn:18088/m/student/leaveRecord")
      .then(({ success, result: { code, name } }) => {
        if (success) {
          state.params.employeeCode = code;
          state.employeeName = name;
          sessionStorage.setItem("code", code);
          sessionStorage.setItem("name", name);
        }
      })
      .then(() => getData());
  } else {
    state.params.employeeCode = sessionStorage.getItem("code");
    state.employeeName = sessionStorage.getItem("name");
    getData();
  }
};

onMounted(() => {
  document.title = "请假记录";
  initState();

  let ainput = document.querySelectorAll(
    ".leaveRecord-warp .ant-picker-input input"
  );
  ainput.forEach((item: any) => {
    item.addEventListener("focus", () => {
      item.setAttribute("readonly", "false");
    });
  });
});
</script>
<style scoped lang="less">
.leaveRecord-warp {
  .content {
    height: calc(100vh - 90px);
    padding: 6px;
    background-color: #eee;
    .add {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 6px;
    }
    :deep(.ant-btn-default:not(:disabled):hover) {
      color: #000 !important;
      border-color: #d9d9d9 !important;
    }
  }
}
</style>
